import type { Router } from 'vue-router';
import NProgress from 'nprogress'; // progress bar

import { usePrjPermissionStore } from '@/store';

export default function setupPermissionGuard(router: Router) {
  router.beforeEach(async (to, _, next) => {
    // 只有在有项目的情况下才需要设置权限
    if (to.path.includes('/project')) {
      const projectId = (to.params.projectId || '') as string;
      const prjPermissionStore = usePrjPermissionStore();
      if (prjPermissionStore.id === projectId) {
        next();
      } else {
        try {
          await prjPermissionStore.setPermission(projectId);
          next();
        } catch (error) {
          next();
        }
      }
    } else {
      next();
    }
    NProgress.done();
  });
}
